package com.mark.common.util.mongo;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import com.mongodb.*;


public class DaoBaseCURD {
	
	private Mongo mg = null;
	private DB db;
	private DBCollection col;
	
	public void init(String dbname,String name){
		try
		{
			if( dbname.isEmpty() ){
				dbname = " base";
			}
			if( name.isEmpty() ){
				name = "collection";
			}
			
			mg = new Mongo();
			db = mg.getDB(dbname);
			col = db.getCollection(name);
		}catch(UnknownHostException e ){
			//e.
			e.printStackTrace();
		}catch(MongoException e){
			e.printStackTrace();
		}
	}
	
	public void destory(){
		if(mg != null )mg.close();
		mg = null;
		db = null;
		col = null;
		System.gc();
	}
	
	public void queryAll(){
		DBCursor cur = col.find();
		while(cur.hasNext()){
			print(cur.next());
		}
	}
	
	/**
	 * 批量插入记录
	 * @param ListRecord
	 */
	public void addBatch(List<DBObject> ListRecord){
		try{
			// list = new ArrayList<DBObject>();
			//DBObject dbo = new BasicDBObject();
			col.insert(ListRecord);			
		}catch( Exception e){
			e.printStackTrace();
		}

	}
	
	/**
	 * 插入单条记录
	 * @param Record
	 */
	public void add(DBObject Record){
		try{
			col.insert(Record);
		}catch( Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 修改mongo db 一条记录
	 */
	public void update(BasicDBObject q,BasicDBObject o){
		col.update(q, o);
	}
	
	/**
	 * 打印日志
	 * @param o
	 */
	public void print(Object o){
		System.out.println(o);
	}

}